<template>
  <div class="home-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><House /></el-icon>
            <span>房产管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加房产
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain>
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain>
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
            <el-button type="warning" @click="handleImport" plain>
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/home.png" alt="Home Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>房产管理</h3>
          <p>高效管理小区房产信息，轻松掌握户主、面积、户型等数据</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属小区">
          <el-select v-model="searchForm.communityId" placeholder="请选择小区" @change="onCommunityChange" clearable>
            <el-option 
              v-for="community in communities" 
              :key="community.id" 
              :label="community.name" 
              :value="community.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="栋数">
          <el-select v-model="searchForm.buildingId" placeholder="请选择栋数" clearable>
            <el-option 
              v-for="building in buildings" 
              :key="building.id" 
              :label="building.name" 
              :value="building.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="户主名称">
          <el-input v-model="searchForm.ownerName" placeholder="请输入户主名称" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>房产列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无房产数据'"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
     
        <el-table-column label="所属栋数" width="120">
          <template #default="scope">
            <div class="building-cell">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ scope.row.buildingName || (scope.row.building ? scope.row.building.name : '未知') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="房产名称" width="120">
          <template #default="scope">
            <div class="home-name">
              <el-icon><House /></el-icon>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="户主名称" width="100">
          <template #default="scope">
            <div class="owner-cell">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.ownerName || (scope.row.owner ? scope.row.owner.name : '未知') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="楼层" width="80">
          <template #default="scope">
            <el-tag size="small" effect="plain" type="info">{{ scope.row.floor }} 层</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="面积" width="100">
          <template #default="scope">
            <el-tag size="small" effect="plain" type="success">{{ scope.row.area }} m²</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="户型" width="80"></el-table-column>
        <el-table-column prop="direction" label="朝向" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column label="创建时间" width="200">
          <template #default="scope">
            <div class="time-cell">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(scope.row.createdAt) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                size="small"
                @click="handleEdit(scope.row)"
                type="primary"
                text
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                size="small"
                @click="handleDelete(scope.row)"
                type="danger"
                text
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-box">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 导入Excel对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px">
      <div class="import-dialog-content">
        <el-alert
          title="请先下载模板，按照模板格式填写数据后上传"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate" size="small">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx/xls文件</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  House, 
  OfficeBuilding, 
  User,
  Calendar,
  Download,
  Upload
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import ExcelUtil from '@/utils/ExcelUtil';

export default {
  name: 'HomeList',
  components: {
    Plus,
    Edit,
    Delete,
    Search,
    House,
    OfficeBuilding,
    User,
    Calendar,
    Download,
    Upload
  },
  data() {
    return {
      searchForm: {
        communityId: '',
        buildingId: '',
        ownerName: ''
      },
      tableData: [],
      communities: [],
      buildings: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      importDialogVisible: false,
      fileList: [],
      importing: false,
      exportLoading: false
    };
  },
  created() {
    // 组件创建时加载数据
    this.fetchCommunities();
    this.fetchHomes();
  },
  methods: {
    // 日期格式化方法
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 获取小区列表
    fetchCommunities() {
      axios.get('/api/communities')
        .then(response => {
          this.communities = response.data;
        })
        .catch(error => {
          console.error('获取小区列表失败:', error);
          ElMessage.error('获取小区列表失败');
        });
    },
    // 根据小区ID加载楼栋列表
    loadBuildings(communityId) {
      if (!communityId) {
        this.buildings = [];
        this.searchForm.buildingId = '';
        return;
      }
      
      axios.get(`/api/buildings/community/${communityId}`)
        .then(response => {
          this.buildings = response.data;
        })
        .catch(error => {
          console.error('获取楼栋列表失败:', error);
          ElMessage.error('获取楼栋列表失败');
        });
    },
    // 监听小区选择变化
    onCommunityChange() {
      this.loadBuildings(this.searchForm.communityId);
    },
    // 执行搜索操作
    onSearch() {
      this.currentPage = 1; // 重置为第一页
      this.fetchHomes();
    },
    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        communityId: '',
        buildingId: '',
        ownerName: ''
      };
      this.buildings = [];
      this.currentPage = 1;
      this.fetchHomes();
    },
    // 获取房产列表数据
    fetchHomes() {
      this.loading = true;
      
      // 构建请求参数
      const params = {
        page: this.currentPage - 1,
        size: this.pageSize
      };
      
      // 添加搜索参数
      if (this.searchForm.buildingId) {
        params.buildingId = this.searchForm.buildingId;
      }
      
      if (this.searchForm.ownerName) {
        params.ownerName = this.searchForm.ownerName;
      }
      
      // 调用API获取房产列表
      axios.get('/api/homes', { params })
        .then(response => {
          console.log('房产列表API响应:', response.data);
          
          // 处理响应数据
          if (response.data && response.data.content) {
            // 分页响应格式
            this.tableData = response.data.content;
            this.total = response.data.totalElements || response.data.totalItems;
          } else if (Array.isArray(response.data)) {
            // 数组响应格式
            this.tableData = response.data;
            this.total = response.data.length;
          } else {
            console.error('未知的响应格式:', response.data);
            this.tableData = [];
            this.total = 0;
          }
          
          // 处理数据，确保字段显示正确
          this.tableData.forEach(item => {
            // 确保栋数名称显示正确
            if (!item.buildingName && item.building) {
              item.buildingName = item.building.name;
            }
            
            // 确保户主名称显示正确
            if (!item.ownerName && item.owner) {
              item.ownerName = item.owner.name;
            }
          });
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取房产列表失败:', error);
          ElMessage.error('获取房产列表失败');
          this.tableData = [];
          this.total = 0;
          this.loading = false;
        });
    },
    handleAdd() {
      this.$router.push('/property/home/add');
    },
    handleEdit(row) {
      this.$router.push({
        path: '/property/home/add',
        query: { id: row.id }
      });
    },
    handleDelete(row) {
      ElMessageBox.confirm(
        `确认要删除房产 ${row.name} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用API删除房产
        axios.delete(`/api/homes/${row.id}`)
          .then(response => {
            ElMessage.success('删除成功');
            // 重新加载数据
            this.fetchHomes();
          })
          .catch(error => {
            console.error('删除房产失败:', error);
            ElMessage.error('删除房产失败');
          });
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }
      
      // 获取所有选中项的ID
      const ids = this.multipleSelection.map(item => item.id);
      
      ElMessageBox.confirm(
        `确认要删除选中的 ${this.multipleSelection.length} 条记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用API批量删除
        axios.delete('/api/homes/batch', { data: ids })
          .then(response => {
            ElMessage.success('批量删除成功');
            // 重新加载数据
            this.fetchHomes();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            ElMessage.error('批量删除失败');
          });
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      // 重新加载数据
      this.fetchHomes();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      // 重新加载数据
      this.fetchHomes();
    },
    // 导出Excel
    async handleExport() {
      try {
        this.exportLoading = true;
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '所属栋数', prop: 'buildingName' },
          { label: '房产名称', prop: 'name' },
          { label: '户主名称', prop: 'ownerName' },
          { label: '楼层', prop: 'floor' },
          { label: '面积(m²)', prop: 'area' },
          { label: '户型', prop: 'type' },
          { label: '朝向', prop: 'direction' },
          { label: '状态', prop: 'status' }
        ];
        
        // 获取所有数据
        const response = await axios.get('/api/homes/all');
        const data = response.data.map(item => {
          // 处理小区和楼栋名称
          if (item.building && typeof item.building === 'object') {
            item.buildingName = item.building.name;
            
            if (item.building.community && typeof item.building.community === 'object') {
              item.communityName = item.building.community.name;
            }
          }
          
          // 处理户主信息
          if (item.owner && typeof item.owner === 'object') {
            item.ownerName = item.owner.name;
          }
          
          return item;
        });
        
        // 导出Excel
        ExcelUtil.exportExcel(data, '房产信息表', header);
        
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    },
    
    // 打开导入对话框
    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },
    
    // 下载导入模板
    async downloadTemplate() {
      try {
        // 创建模板数据
        const templateData = [
          {
            communityName: '阳光花园',
            buildingName: '1栋',
            name: '1单元101',
            ownerName: '张三',
            floor: '1',
            area: '120',
            type: '三室两厅',
            direction: '南北通透',
            status: '已售出'
          }
        ];
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '所属栋数', prop: 'buildingName' },
          { label: '房产名称', prop: 'name' },
          { label: '户主名称', prop: 'ownerName' },
          { label: '楼层', prop: 'floor' },
          { label: '面积(m²)', prop: 'area' },
          { label: '户型', prop: 'type' },
          { label: '朝向', prop: 'direction' },
          { label: '状态', prop: 'status' }
        ];
        
        // 导出模板
        ExcelUtil.exportExcel(templateData, '房产信息导入模板', header);
        
        ElMessage.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 文件选择变更
    handleFileChange(file) {
      this.fileList = [file];
    },
    
    // 提交导入
    async submitImport() {
      if (!this.fileList.length) {
        ElMessage.warning('请选择要导入的Excel文件');
        return;
      }
      
      try {
        this.importing = true;
        
        // 读取Excel文件
        const file = this.fileList[0].raw;
        
        // 定义表头映射
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '所属栋数', prop: 'buildingName' },
          { label: '房产名称', prop: 'name' },
          { label: '户主名称', prop: 'ownerName' },
          { label: '楼层', prop: 'floor' },
          { label: '面积(m²)', prop: 'area' },
          { label: '户型', prop: 'type' },
          { label: '朝向', prop: 'direction' },
          { label: '状态', prop: 'status' }
        ];
        
        // 解析Excel数据
        const importedData = await ExcelUtil.importExcel(file, header);
        
        // 处理导入数据，将小区名称和楼栋名称转换为ID
        const processedData = importedData.map(item => {
          // 查找小区ID
          const community = this.communities.find(c => c.name === item.communityName);
          if (community) {
            item.communityId = community.id;
            
            // 查找楼栋ID
            const building = this.buildings.find(b => b.name === item.buildingName && b.communityId === community.id);
            if (building) {
              item.buildingId = building.id;
            }
          }
          
          return item;
        });
        
        // 提交到后端
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await axios.post('/api/homes/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(`导入成功，成功导入${response.data.successCount || importedData.length}条数据`);
        this.importDialogVisible = false;
        this.fetchHomes(); // 刷新列表
      } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.importing = false;
      }
    }
  }
};
</script>

<style scoped>
.home-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-select .el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.building-cell,
.home-name,
.owner-cell,
.time-cell {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.building-cell .el-icon,
.home-name .el-icon,
.owner-cell .el-icon,
.time-cell .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

.building-cell .el-icon {
  color: #409EFF;
}

.home-name .el-icon {
  color: #67C23A;
}

.owner-cell .el-icon {
  color: #E6A23C;
}

.time-cell .el-icon {
  margin-right: 8px;
  color: #409EFF;
  font-size: 16px;
}

.time-cell span {
  font-size: 14px;
  color: #606266;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

/* 导入导出相关样式 */
.import-dialog-content {
  padding: 10px 0;
}

.template-download {
  margin-bottom: 20px;
  text-align: center;
}

.excel-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}
</style>
